package com.leaf.u_spring.chapter12;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

/**
 * 
 * Spring Data MongoDB的配置
 * 扩展AbstractMongoConfiguration
 *
 */
@Configuration
@EnableMongoRepositories(basePackages="com.adagio.db")	//启用MongoDB的Repository功能
public class MongoConfig2 extends AbstractMongoConfiguration {

	@Override
	protected String getDatabaseName() {
		return "OrdersDB";		//指定数据库名
	}

	@Autowired
	private Environment env;
	
	@Override
	public Mongo mongo() throws Exception {
//		return new MongoClient();		//创建Mongo客户端
		
		//如果MongoDB服务器运行在其他的机器上
//		return new MongoClient("mongoServer");
		
		//如果MongoDB服务器监听的端口不是默认端口27017
//		return new MongoClient("mongoServer", 37017);
		
		//如果MongoDB服务器在生产配置上，启用了认证功能
		MongoCredential credential = MongoCredential.createCredential(
				env.getProperty("mongo.username") , "OrdersDB", 
				env.getProperty("mongo.password").toCharArray());
		return new MongoClient(
				new ServerAddress("localhost", 37017),
				Arrays.asList(credential));
	}

	
}
